package com.iot.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.iot.core.constant.ResponseEnum;
import com.iot.core.exception.BDException;
import com.iot.core.redis.RedisOperate;
import com.iot.core.utils.MD5Utils;
import com.iot.core.utils.R;
import com.iot.server.common.utils.VerifyUtil;
import com.iot.server.domain.SysUserDO;
import com.iot.server.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Map;

@Controller
public class LoginController{
    @Autowired
    private UserService userService;
    @Autowired
    RedisOperate redisOperate;
    /**
     * 账号锁定
     */
    private static final String LOCKED = "-1";

    @GetMapping("/login")
    R login() {
        return R.fromEnum(ResponseEnum.UNLOGIN);
    }

    @RequestMapping(value = {"/user/login"}, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public R login(@RequestBody JSONObject jsonObject,HttpServletRequest request) {
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");
//        String verifyCode = jsonObject.getString("verifyCode");
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return R.error("账号或密码为空");
        }
        SysUserDO user = userService.findByUserName(username);
        if (null == user) {
            return R.error("账号不存在");
        }
        // 账号锁定
        if (user.getLocked().equals(LOCKED)) {
            return R.error("账号已被锁定,请联系管理员");
        }
        if (!MD5Utils.encrypt(user.getUserId(), password).equals(user.getPassword())) {
            return R.error("密码错误");
        }
        //判断验证码是否有效
//        String sessionId = request.getSession().getId();
//        System.out.println("checkVerifyImg:" + sessionId);
//        if (!redisOperate.exists(sessionId + "_VerifyCode")) {
//            throw new BDException("验证码失效，请重新获取验证码");
//        }
//        String verifyImg = redisOperate.get(sessionId + "_VerifyCode");
//        if (!verifyCode.trim().toUpperCase().equals(verifyImg)) {
//            //清除验证码
//            redisOperate.del(sessionId + "_VerifyCode");
//            throw new BDException("验证码错误");
//        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserId(), password);
        try{
            subject.login(token);
            //清除验证码
//            redisOperate.del(sessionId + "_VerifyCode");
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("token", subject.getSession().getId());
            return R.ok(jsonObject1);
        }catch (AuthenticationException e) {
            return R.error("用户名或密码错误");
        }

    }

    @RequestMapping(value = {"/user/logout"}, method = RequestMethod.GET)
    @ResponseBody
    public R logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return R.ok("sucess", "sucess");
    }

    @RequestMapping(value = {"/user/info"}, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public R info(@RequestParam Map<String, Object> params) {
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("roles", Arrays.asList("admin"));
        jsonObject2.put("avatar", "");
        jsonObject2.put("introduction", "HELLO WORLD");
        jsonObject2.put("name", "Admin");
        return R.ok(jsonObject2);
    }

    @RequestMapping(value = "/getVerifyImg", method = {RequestMethod.POST, RequestMethod.GET})
    protected void createImg(HttpServletRequest req, HttpServletResponse res) throws IOException {
        //1.生成随机的验证码及图片
        Object[] objs = VerifyUtil.createImage();
        //2.将验证码存入redis,60有效
        String sessionId = req.getParameter("appUUID");
        if (StringUtils.isEmpty(sessionId)) {
            sessionId = req.getSession().getId();
        }
        System.out.println("createVerifyImg:" + sessionId);
        redisOperate.set(sessionId + "_VerifyCode", (String) objs[0], 60);
        //3.将图片输出给浏览器
        BufferedImage img = (BufferedImage) objs[1];
        res.setContentType("image/png");
        //服务器自动创建输出流，目标指向浏览器
        OutputStream os = res.getOutputStream();
        ImageIO.write(img, "png", os);
        os.close();
    }
}
